from util import Observer
from message import *
import sys_server

class Timer():
    def __init__(self, target, id, interval):
        self.target = target
        self.id = id
        self.interval = interval
        self.tickcnt = interval

    def tick(self):
        self.tickcnt = self.tickcnt - 500
        if self.tickcnt <= 0:
            self.tickcnt = self.interval
            self.target.message(Msg(MSG_TIMER, None, self,id))

class __TimerManager(Observer):
    timer_list = []
    def __init__(self):
        sys_server.set_msg_observer(MSG_TIMER, self)
        
    def sys_message(self, msg):
        for t in self.timer_list:
            t.tick()

    def start_timer(self, target, id, interval):
        timer = Timer(target, id, interval)
        self.timer_list.append(timer)

    def kill_timer(self, id):
        for t in self.timer_list:
            if t.id == id:
                self.timer_list.remove(t)

    def kill_all_timer():
        self.timer_list = []
        
__timer_manager = __TimerManager()

def get_timer_manager():
    return __timer_manager
